<template>
	<view>
		<!-- 未询问前 -->
		<view v-if="displayFirst"  class="ark-body">
			<view class="ark-contain">
				<view class="conatin-title">
					今天能帮您些什么？
				</view>
			</view>
			<view class="contain-bottom">
				<view class="contain-list" @click='upxianz()'>
					如何发布闲置物品
					<view class="list-item" >
						来帮助我卖出闲置物品
					</view>
				</view>
				<view class="contain-list" @click='upneed()'>
					如何发布需求物品
					<view class="list-item">
						以帮助我寻找到需要的物品
					</view>
				</view>
			</view>
		</view>
		<!-- 询问后 -->
		<view  v-if="!displayFirst" class="ark-contains">
			<scroll-view :scroll-top="scrollTop" scroll-y="true">
			<view class="chatConten" v-for="(chatConten,index) in finalChat" :key='index' >
				<view class="userArk">
					<view>
						<img class="img" src="@/pages/ask/send.png" alt="" />
					</view>
					<view class="body">
						<view class="body-name">
							您
						</view>
						<view class="body-conatin">
							{{ chatConten.user }}
						</view>
					</view>
				</view>
				<view class="userArk">
					<view>
						<img class="img" src="@/pages/ask/robot.png" alt="" />
					</view>
					<view class="body">
						<view class="body-name">
							AI小助手
						</view>
						<view class="body-conatin">
							{{ chatConten.aiDisplay  }}
						</view>
					</view>
				</view>
			</view>
			</scroll-view>
		</view>
		<view class="ark-bottom">
			<view class="ark-neibu">
				<u-input style="padding-right: 70rpx;" class="inputs" maxlength='80' border="true" :cursor-spacing="20" border-color='gray' v-model="userInput" placeholder="给'AI小助手'发送消息" type="textarea" width="500px"  height="45" focus="true" auto-height="true"  />
				<view class="send">
					<!-- <img v-if="loading"  @click='start()' src="@/pages/ask/send.png" class="send" /> -->
					<view   @click='start()' v-if="!loading" class="up">
						发送
					</view>
					<view  v-if="loading" class="down">
						发送中
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { onLoad} from '@dcloudio/uni-app';
	import CryptoJS from 'crypto-js';
	import { Base64 } from 'js-base64';
	export default {
		data() {
			return {
				appId: '27d60a1b',
				status: 'init',
				ttsWS: null,
				totalRes: '',
				userInput: '',
				aiContentRequest: '',
				finalChat: [],
				loading:false,
				displayFirst:true,
				items: [
					{title:'如何发布闲置物品',contain:'来帮助我卖出闲置物品'},
					{title:'如何发布需求物品',contain:'以帮助我寻找到需要的物品'}
				],
				isVisible: [true, true],
			}
		},
		methods: {
			// 鉴权
			getWebsocketUrl() {
				return new Promise((resolve, reject) => {
				   const apiKey = '5176c72a43b3c0e3d11b5421d603afde';
				   const apiSecret = 'OTRiMDg1MzJiYzI1Yzc3OTdkMDczMmUy';
				   const url = 'wss://spark-api.xf-yun.com/v3.5/chat'; //这里使用的是星火大模型3.x版本
				   const host = 'spark-api.xf-yun.com';
				   const date = new Date().toUTCString();
				   const algorithm = 'hmac-sha256';
				   const headers = 'host date request-line';
				   const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v3.5/chat HTTP/1.1`;
				   const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
				   const signature = CryptoJS.enc.Base64.stringify(signatureSha);
				   const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
				   const authorization = Base64.encode(authorizationOrigin);
				   const finalUrl = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
				   console.log('22222',finalUrl)
				   resolve(finalUrl);
				});
			},
		   setStatus(status) {
			 this.status = status;
		   },
			connectWebSocket() {
				this.setStatus('ttsing');
				this.getWebsocketUrl().then((url) => {
					this.ttsWS = wx.connectSocket({
					        url: url,
					        success: () => {
					          console.log('WebSocket连接创建成功');
					        },
					        fail: () => {
					          console.log('WebSocket连接创建失败');
					          this.setStatus('error');
					        }
					      });
					
					      wx.onSocketOpen(() => {
					        this.webSocketSend();
					      });
					
					      wx.onSocketMessage((result) => {
					        this.result(result.data);
					      });
					
					      wx.onSocketError((error) => {
					        console.error('WebSocket错误', error);
					        this.setStatus('error');
					      });
					
					      wx.onSocketClose(() => {
					        console.log('WebSocket已关闭');
					        this.setStatus('init');
					      });
				});
			},
			   webSocketSend() {
				 let that = this
				 const params = {
				   header: {
					 app_id: this.appId,
					 uid: '随意',
				   },
				   parameter: {
					 chat: {
					   domain: 'generalv3.5',//如果是chat3.5这里也需要进行相应修改
					   temperature: 0.5,
					   max_tokens: 1024
					 },
				   },
				   payload: {
					 message: {
					   text: [
							{"role":"system","content":"你是一个熟悉这个校园智能闲物交易小程序的AI助手，你不仅要回答用户关于这个小程序的问题，还要保持你原有的功能。你熟悉这个小程序的使用方法，包括但不限于如何发布商品，交易流程，如果有用户问到你相关问题，你将会从下面这个使用手册中提取内容来回答用户。智能闲物交易小程序使用手册：1.如何发布闲置物品：点击小程序正下方的发布按钮，进入 发布页面，发布类型选择闲置，输入要卖出的闲置的具体信息即可，发布求购物品也是同理2.交易流程：联系卖家 -> 约定交易地点 -> 完成交易"},
							{"role": "user", "content": '你是谁'},
							{"role":"assistant","content":"....."},
							{"role": "user", "content": that.userInput}
						 ]
					 },
				   },
				 };
				 console.log(JSON.stringify(params));
				 wx.sendSocketMessage({
					 data:JSON.stringify(params)
				 })
			   },
			   start() {
				 if(this.userInput != ''){
					 this.connectWebSocket();
					 this.loading = true
					 this.displayFirst = false
					 this.totalRes = '';
					 this.aiContentRequest = ''
				 }
				 
			   },
			   upxianz(){
				   this.userInput = '如何发布闲置物品'
				   this.start()
			   },
			    upneed(){
			   		this.userInput = '如何发布需求物品'
					this.start()
					},
			   requestHandle(requestData) {//处理request
				 this.aiContentRequest = this.aiContentRequest + requestData.payload.choices.text[0].content
			  },
			   result(resultData) {
				 let jsonData = JSON.parse(resultData);
				 //console.log(jsonData)
				 this.totalRes += resultData;
				 //this.$refs.outputText.value = this.totalRes;
				 //加入到ai回答中
				 if(jsonData.header.status!==2){//不为结束就进行添加
					 this.requestHandle(jsonData)
				 }else {
					 let contentSomething = {
						 ai: this.aiContentRequest,
						 user: this.userInput
					 }
					 this.finalChat.push(contentSomething)
					 this.userInput = ''
					 this.loading = false
					   this.$nextTick(() => {
						   this.displayAIResponse(contentSomething); // 在 $nextTick 中调用，确保视图已更新
						 });
				 }
				 if (jsonData.header.code !== 0) {
				   // console.error(`${jsonData.header.code}:${jsonData.header.message}`);
				   return;
				 }
				 if (jsonData.header.code === 0 && jsonData.header.status === 2) {
				   this.ttsWS.close();
				   this.setStatus('init');
				 }
			   },
			   displayAIResponse(chat) {
					 let index = this.finalChat.indexOf(chat);
					 let i = 0;
					 const interval = setInterval(() => {
					   if (i < chat.ai.length) {
						 this.$set(this.finalChat[index], 'aiDisplay', chat.ai.substring(0, i + 1));
						 i++;
					   } else {
						 clearInterval(interval);
					   }
					 }, 100);
				   },
			}
					
		}
</script>

<style lang="scss">
.ark-contain{
	display: flex;
	justify-content: center; /* 水平居中 */
	padding-top: 40vh;
	height: 52vh;
	.conatin-title{
		font-size: 24px;
		font-weight: 600;
		text-align: center;
	}
}
.contain-bottom{
		padding-top: 20px;
		display: flex;
		flex-direction: column; /* 使子元素垂直排列 */
		align-items: center; /* 水平居中对齐 */
		width: 100%; /* 确保容器宽度为100% */
		.contain-list{
			border: 1px solid #aaaaaa;
			height: 120rpx;
			width: 600rpx;
			border-radius: 15rpx;
			margin-top: 20rpx;
			padding: 20rpx 20rpx;
			font-weight: 600;
			font-size: 14px;
			.list-item{
				font-size: 12px;
				color: #aaaaaa;
				margin-top: 5rpx;
			}
		}
	}
.ark-bottom{
	display: flex;
	flex-direction: column; /* 使子元素垂直排列 */
	align-items: center; /* 水平居中对齐 */
	.ark-neibu{
		display: flex;
		.inputs{
			width: 600rpx;
			position: fixed;
			left: 80rpx;
			bottom: 50rpx;
			
		}
		.send{
			position: fixed;
			right: 88rpx;
			bottom: 65rpx;
			width: 50rpx;
			height: 50rpx;
		}
		.up{
			width: 100rpx;
			position: fixed;
			right: 50rpx;
			bottom: 65rpx;
		}
		.down{
			width: 120rpx;
			position: fixed;
			right: 50rpx;
			bottom: 65rpx;
			color: #aaaaaa;
		}
	}
}
body{
	height: 100%;
}
.ark-contains{
	display: flex;
	padding-top: 2vh;
	height: 82vh;
}
.userArk{
	display: flex;
	margin-bottom: 60rpx;
	.img{
		width: 55rpx;
		height: 55rpx;
		border-radius: 25rpx;
		margin: 0 25rpx;
		border: 1px solid #aaaaaa;
	}
	.body-name{
		font-size: 16px;
		font-weight: 600;
		margin-bottom: 10rpx;
	}
		
	.body-conatin{
		font-size: 16px;
		margin-bottom: 10rpx;
		width: 550rpx;
	}
}
</style>
